package com.easyticket.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.easyticket.util.HttpClientUtil;

/**
 * 动态秘钥
 * 
 * @author lenovo
 *
 */
public class Device {

	private static final Logger logger = Logger.getLogger(Device.class);

	public static void init() {
//		JSONObject jsonObject = getDeviceId();
//		String railExpiration = jsonObject.getString("RAIL_EXPIRATION");
//		String railDeviceid = jsonObject.getString("RAIL_DEVICEID");
		String railExpiration = "1577176704032";
		String railDeviceid = "qPx1Z7zKdLaFvzbeFmnQDZyMp5bVSh-_6vSgADttqu6CgAq2AnoqIsZuvb1DJmvMps7kKRh2xRbhIjYfEN8LMEmKPOMVBvzswW_M7jsiSxVehcOHUcpgUGJT5LGltov1dFGnXm-ag6aBVUzCGXaraP7_EKZfyKHk";

			BasicClientCookie exp = new BasicClientCookie("RAIL_EXPIRATION", railExpiration);
			exp.setDomain(HeaderSotre.host);
			exp.setPath("/");
			CookieStore.cookieStore.addCookie(exp);

			BasicClientCookie DEVICEID = new BasicClientCookie("RAIL_DEVICEID", railDeviceid);
			DEVICEID.setDomain(HeaderSotre.host);
			DEVICEID.setPath("/");
			CookieStore.cookieStore.addCookie(DEVICEID);
	}

	/**
	 * exp
	 * 
	 * @return exp dfp
	 */

	public static JSONObject getDeviceId() {
		try {

			String result = HttpClientUtil.sendGet("http://rail.51ab.top/api/getRailId");
			return JSON.parseObject(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getAlgId() {
		try {
			String url = "https://kyfw.12306.cn/otn/HttpZF/GetJS";
			HttpGet get = new HttpGet(url);
			get.addHeader("Referer", "https://www.12306.cn/index/index.html");
			get.addHeader("User-Agent", HeaderSotre.userAgent);
			CloseableHttpResponse re = HttpClientUtil.getClient().execute(get);
			String reuslt = EntityUtils.toString(re.getEntity());
			Pattern p = Pattern.compile("algID\\\\x3d(.*?)\\\\x26");
			Matcher m = p.matcher(reuslt);
			while (m.find()) {
				return m.group(1);
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
